﻿import React, { useState, useEffect, useRef } from "react";
import {
  MapContainer,
  TileLayer,
  Marker,
  Popup,
  useMapEvents,
} from "react-leaflet";
import "leaflet/dist/leaflet.css";
import Draggable from "react-draggable"; // Import Draggable component
import * as L from "leaflet";
import "./Routes.css";

delete L.Icon.Default.prototype._getIconUrl;

function LocationMarker({ onLocationFound }) {
  const [position, setPosition] = useState(null);
  const map = useMapEvents({
    locationfound(e) {
      setPosition(e.latlng);
      map.flyTo(e.latlng, map.getZoom());

      onLocationFound(e.latlng); // Call the callback function
    },
  });

  L.Icon.Default.mergeOptions({
    iconRetinaUrl: require("leaflet/dist/images/marker-icon-2x.png"),
    iconUrl: require("leaflet/dist/images/marker-icon.png"),
    shadowUrl: require("leaflet/dist/images/marker-shadow.png"),
    iconSize: [32, 48],
  });

  useEffect(() => {
    map.locate();
  }, [map]);

  return position === null ? null : (
    <Marker
      position={position}
      icon={L.icon({
        iconUrl: require("leaflet/dist/images/marker-icon.png"),
        shadowUrl: require("leaflet/dist/images/marker-shadow.png"),
        iconSize: [32, 48],
      })}
    >
      <Popup>You are here</Popup>
    </Marker>
  );
}

function Routes() {
  const [selectedMode, setSelectedMode] = useState("road");
  const [quantity, setQuantity] = useState("");
  const [userLocation, setUserLocation] = useState(null);
  const mapRef = useRef(null);

  const [sortedCompanies, setSortedCompanies] = useState([]);

  const companies = [
    {
      name: "Teknion Roy & Breton Inc. - Head Office",
      lat: 46.805356,
      lng: -71.179788,
    },
    {
      name: "Teknion Roy & Breton Inc. - Logistic and Client Service Centre",
      lat: 46.805356,
      lng: -71.179788,
    },
    {
      name: "Teknion Roy & Breton Inc. - RB Tek",
      lat: 46.725871,
      lng: -71.222352,
    },
    {
      name: "Teknion Roy & Breton Inc. - Roy & Breton",
      lat: 46.864218,
      lng: -70.972776,
    },
    {
      name: "Teknion Roy & Breton Inc. - Teknion Concept",
      lat: 46.805356,
      lng: -71.179788,
    },
    {
      name: "Teknion Roy & Breton Inc. - Teknion LS",
      lat: 46.557113,
      lng: -71.768014,
    },
    {
      name: "Teknion Roy & Breton Inc. - Teknion Québec",
      lat: 46.980819,
      lng: -70.564911,
    },
    {
      name: "Teknion Roy & Breton Inc.-Client Service Centre",
      lat: 46.804966,
      lng: -71.180126,
    },
    { name: "Scott Construction Group", lat: 49.2609, lng: -122.9164 },
    { name: "Trico Homes", lat: 50.9499, lng: -114.1353 },
    { name: "Rise", lat: 45.9636, lng: -66.6431 },
    { name: "Chandos Construction", lat: 53.5396, lng: -113.5071 },
    { name: "Sky Fire Energy", lat: 51.0275, lng: -114.0431 },
  ];

  useEffect(() => {
    if (userLocation) {
      const companiesWithEmissions = companies.map((company) => {
        const distance = getDistance(company.lat, company.lng);
        const emissions = getEmissions(distance);
        return { ...company, emissions, distance };
      });

      // Sort companies by emissions (ascending order)
      const sorted = [...companiesWithEmissions].sort(
        (a, b) => a.emissions - b.emissions
      );
      setSortedCompanies(sorted);
    }
  }, [userLocation, companies, quantity, selectedMode]); // Update when these dependencies change

  const transportEmissionFactors = {
    road: 0.1065,
    sea: 0.01614,
    air: 0.59943,
    rail: 0.02556,
  };

  const handleModeChange = (event) => {
    setSelectedMode(event.target.value);
  };

  const handleQuantityChange = (event) => {
    setQuantity(event.target.value);
  };

  useEffect(() => {
    if (mapRef.current) {
      const markersGroup = new L.featureGroup(
        companies.map((company) => L.marker([company.lat, company.lng]))
      );
      mapRef.current.fitBounds(markersGroup.getBounds());
    }
  }, [companies]);

  const handleLocationFound = (location) => {
    setUserLocation(location);
  };

  const getDistance = (companyLat, companyLng) => {
    if (userLocation) {
      const from = userLocation;
      const to = L.latLng(companyLat, companyLng);
      const distance = from.distanceTo(to) / 1000;
      return distance.toFixed(2);
    }
    return null;
  };

  const getEmissions = (distance) => {
    const dist = parseFloat(distance);
    const qty = parseFloat(quantity);
    const tef = transportEmissionFactors[selectedMode];
    const emissions = (tef * dist * qty) / 1000;
    return emissions.toFixed(2);
  };

  const getIconColor = (emissions) => {
    // Calculate color thresholds based on emissions
    const threshold1 = 100; // Example threshold - adjust as needed
    const threshold2 = 200; // Example threshold - adjust as needed

    if (emissions <= threshold1) {
      return "green";
    } else if (emissions <= threshold2) {
      return "yellow";
    } else {
      return "red";
    }
  };

  return (
    <div className="RotuesContainer">
      <h2 className="title">Routes</h2>

      <div className="content">
        <div className="selectCon">
          <label htmlFor="transportMode">Select Transport Mode:</label>
          <select
            className="select selectEle"
            id="transportMode"
            value={selectedMode}
            onChange={handleModeChange}
          >
            <option value="road">Road</option>
            <option value="rail">Sea</option>
            <option value="air">Freight</option>
            <option value="sea">Rail</option>
          </select>
        </div>

        <div className="mt20">
          <label htmlFor="quantity">Quantity (kg):</label>
          <input
            className="input inputEle"
            type="number"
            id="quantity"
            value={quantity}
            onChange={handleQuantityChange}
          />
        </div>
      </div>

      {/* Company list */}
      <Draggable>
        <div className="company-list mt20">
          {" "}
          {/* Add a class for styling */}
          <h3 className="title">Companies by Emission Level</h3>
          <ul>
            {sortedCompanies.map((company) => (
              <li
                key={company.name}
                style={{ color: getIconColor(company.emissions) }}
              >
                {company.name} - {company.emissions} kgCO₂e ({company.distance}{" "}
                km)
              </li>
            ))}
          </ul>
        </div>
      </Draggable>

      <MapContainer
        style={{ height: "100vh" }}
        center={[46.805356, -71.179788]}
        zoom={5}
        scrollWheelZoom={false}
        ref={mapRef}
      >
        <TileLayer
          attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />

        <LocationMarker onLocationFound={handleLocationFound} />
        {companies.map((company) => {
          const distance = getDistance(company.lat, company.lng);
          const emissions = getEmissions(distance);
          const iconColor = getIconColor(emissions);

          return (
            <Marker
              key={company.name}
              position={[company.lat, company.lng]}
              icon={L.icon({
                iconUrl: require(`./image/${iconColor}-icon.png`),
                shadowUrl: require("leaflet/dist/images/marker-shadow.png"),
                iconSize: [30, 33],
              })}
            >
              <Popup>
                {company.name} <br />
                {userLocation && (
                  <span>
                    Distance: {distance} km <br />
                    Emissions: {emissions} kgCO₂e
                  </span>
                )}
              </Popup>
            </Marker>
          );
        })}
      </MapContainer>
    </div>
  );
}

export default Routes;
